package com.platform.web.controller.base;

import java.util.List;

import com.platform.base.domain.BaseFactory;
import com.platform.base.service.ICollectorInfoService;
import com.platform.common.constant.UserConstants;
import com.platform.common.core.domain.Ztree;
import com.platform.common.utils.StringUtils;
import com.platform.common.utils.redis.RedisUtil;
import com.platform.framework.util.ShiroUtils;
import com.platform.system.domain.SysDept;
import com.platform.system.domain.SysUser;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.platform.common.annotation.Log;
import com.platform.common.enums.BusinessType;
import com.platform.base.domain.BaseLocation;
import com.platform.base.service.IBaseLocationService;
import com.platform.common.core.controller.BaseController;
import com.platform.common.core.domain.AjaxResult;
import com.platform.common.utils.poi.ExcelUtil;
import com.platform.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 住户信息Controller
 * 
 * @author wangqi
 * @date 2020-09-24
 */
@Controller
@RequestMapping("/base/location")
public class BaseLocationController extends BaseController
{
    private String prefix = "base/location";

    @Autowired
    private IBaseLocationService baseLocationService;

    @Autowired
    private RedisUtil redisUtil;

    @RequiresPermissions("base:location:view")
    @GetMapping()
    public String location()
    {
        return prefix + "/location";
    }



    /**
     * 查询住户信息列表
     */
    @RequiresPermissions("base:location:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(BaseLocation baseLocation)
    {
        startPage();
        List<BaseLocation> list = baseLocationService.selectBaseLocationList(baseLocation);
        return getDataTable(list);
    }

    /**
     * 查询住户信息列表
     */
    @RequiresPermissions("base:location:datalist")
    @PostMapping("/datalist")
    @ResponseBody
    public TableDataInfo datalist(BaseLocation baseLocation)
    {
        startPage();
        List<BaseLocation> datalist = baseLocationService.selectBaseLocationDataList(baseLocation);
        return getDataTable(datalist);
    }

    /**
     * @Author 王琦
     * @Description //住户信息导入
     * @Date 2020/6/19 19:56
     * @Param [file, updateSupport]
     * @return com.platform.common.core.domain.AjaxResult
     */
    @Log(title = "住户信息", businessType = BusinessType.IMPORT)
    @RequiresPermissions("base:location:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<BaseLocation> util = new ExcelUtil<BaseLocation>(BaseLocation.class);
        List<BaseLocation> locationList = util.importExcel(file.getInputStream());
        String operName = ShiroUtils.getSysUser().getLoginName();
        String message = baseLocationService.importLocation(locationList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    /**
     * @Author 王琦
     * @Description //导入模板
     * @Date 2020/6/19 19:56
     * @Param []
     * @return com.platform.common.core.domain.AjaxResult
     */
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<BaseLocation> util = new ExcelUtil<BaseLocation>(BaseLocation.class);
        return util.importTemplateExcel("住户信息");
    }

    /**
     * 导出住户信息列表
     */
    @RequiresPermissions("base:location:export")
    @Log(title = "住户信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(BaseLocation baseLocation)
    {
        List<BaseLocation> list = baseLocationService.selectBaseLocationList(baseLocation);
        for(BaseLocation location : list){
            String[] ans = location.getAncestors().split(",");
            int i = 0;
            for(String an : ans){
                if(!an.equals("0")){
                    String anName = "";
                    BaseLocation f = null;
                    if(redisUtil.hHasKey("location", an)){
                        f = (BaseLocation)redisUtil.hget("location", an);
                        anName = f.getLocationName();
                    }else{
                        f = baseLocationService.getById(an);
                        if(f != null){
                            anName = f.getLocationName();
                            redisUtil.hset("location", an, f);
                        }
                    }

                    if(i == 0){
                        location.setParent1(anName);
                    }else if(i == 1){
                        location.setParent2(anName);
                    }else if(i == 2){
                        location.setParent3(anName);
                    }else if(i == 3){
                        location.setParent4(anName);
                    }else if(i == 4){
                        location.setParent5(anName);
                    }
                    i++;
                }
            }
        }
        ExcelUtil<BaseLocation> util = new ExcelUtil<BaseLocation>(BaseLocation.class);
        return util.exportExcel(list, "住户信息");
    }

    /**
     * 新增住户信息
     */
    @GetMapping("/add/{parentId}")
    public String add(@PathVariable("parentId") Long parentId, ModelMap mmap)
    {
        mmap.put("location", baseLocationService.getById(parentId));
        return prefix + "/add";
    }

    /**
     * 新增保存住户信息
     */
    @RequiresPermissions("base:location:add")
    @Log(title = "住户信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(@Validated BaseLocation baseLocation)
    {
        if (UserConstants.LOCATION_NAME_NOT_UNIQUE.equals(baseLocationService.checkLocationNameUnique(baseLocation)))
        {
            return error("新增住户'" + baseLocation.getLocationName() + "'失败，住户名称已存在");
        }
        BaseLocation f = baseLocationService.getById(baseLocation.getParentId());
        if(Integer.parseInt(f.getLocationType()) > Integer.parseInt(baseLocation.getLocationType())){
            return error("新增住户'" + baseLocation.getLocationName() + "'失败，地址类型选择错误");
        }
        baseLocation.setCreateBy(ShiroUtils.getLoginName());
        return toAjax(baseLocationService.insertBaseLocation(baseLocation));
    }

    /**
     * 修改住户信息
     */
    @GetMapping("/edit/{locationId}")
    public String edit(@PathVariable("locationId") Long locationId, ModelMap mmap)
    {
        BaseLocation baseLocation = baseLocationService.getById(locationId);
        if (StringUtils.isNotNull(baseLocation) && 0L == locationId)
        {
            baseLocation.setParentName("无");
        }else{
            baseLocation.setParentName(baseLocationService.getById(baseLocation.getParentId()).getLocationName());
        }
        mmap.put("baseLocation", baseLocation);
        return prefix + "/edit";
    }

    /**
     * 修改保存住户信息
     */
    @RequiresPermissions("base:location:edit")
    @Log(title = "住户信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(@Validated BaseLocation baseLocation)
    {
        if (UserConstants.LOCATION_NAME_NOT_UNIQUE.equals(baseLocationService.checkLocationNameUnique(baseLocation)))
        {
            return error("修改住户'" + baseLocation.getLocationName() + "'失败，住户名称已存在");
        }
        else if (baseLocation.getParentId().equals(baseLocation.getLocationId()))
        {
            return error("修改住户'" + baseLocation.getLocationName() + "'失败，上级住户不能是自己");
        }
        BaseLocation f = baseLocationService.getById(baseLocation.getParentId());
        if(Integer.parseInt(f.getLocationType()) > Integer.parseInt(baseLocation.getLocationType())){
            return error("修改住户'" + baseLocation.getLocationName() + "'失败，地址类型选择错误");
        }
        baseLocation.setUpdateBy(ShiroUtils.getLoginName());
        return toAjax(baseLocationService.updateBaseLocation(baseLocation));
    }

    /**
     * 删除住户信息
     */
    @RequiresPermissions("base:location:remove")
    @Log(title = "住户信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove/{locationId}")
    @ResponseBody
    public AjaxResult remove(@PathVariable("locationId") Long locationId)
    {
        if (baseLocationService.selectLocationCount(locationId) > 0)
        {
            return AjaxResult.warn("存在下级住户信息,不允许删除");
        }
        int count = baseLocationService.checkLocationExistEquipment(locationId);
        if(count == 1){
            return AjaxResult.warn("住户信息下存在采集器信息,不允许删除");
        }
        if(count == 2){
            return AjaxResult.warn("住户信息下存在阀门信息,不允许删除");
        }
        if(count == 3){
            return AjaxResult.warn("住户信息下存在热表信息,不允许删除");
        }
        if(count == 4){
            return AjaxResult.warn("住户信息下存在温度采集器信息,不允许删除");
        }
        return toAjax(baseLocationService.deleteBaseLocationById(locationId));
    }

    /**
     * 校验住户信息是否唯一
     */
    @PostMapping("/checkLocationNameUnique")
    @ResponseBody
    public String checkLocationNameUnique(BaseLocation baseLocation)
    {
        return baseLocationService.checkLocationNameUnique(baseLocation);
    }

    /**
     * 选择住户树
     *
     * @param locationId 住户ID
     * @param excludeId 排除ID
     */
    @GetMapping(value = { "/selectLocationTree/{locationId}", "/selectLocationTree/{locationId}/{excludeId}" })
    public String selectLocationTree(@PathVariable("locationId") Long locationId,
                                 @PathVariable(value = "excludeId", required = false) String excludeId, ModelMap mmap)
    {
        BaseLocation baseLocation = baseLocationService.getById(locationId);
        if(baseLocation==null){
            baseLocation = new BaseLocation();
        }
        mmap.put("location", baseLocation);
        mmap.put("excludeId", excludeId);
        return prefix + "/tree";
    }

    /**
     * 加载部门列表树
     */
    @GetMapping(value = { "/treeData", "/treeData/{locationType}" })
    @ResponseBody
    public List<Ztree> treeData(@PathVariable(value = "locationType", required = false) String locationType)
    {
        if(locationType==null){
            locationType = "05";
        }
        BaseLocation baseLocation = new BaseLocation();
        baseLocation.setLocationType(locationType);
        List<Ztree> ztrees = baseLocationService.selectLocationTree(baseLocation);
        return ztrees;
    }

    /**
     * 加载部门列表树（排除下级）
     */
    @GetMapping("/treeData/{locationType}/{excludeId}")
    @ResponseBody
    public List<Ztree> treeDataExcludeChild(@PathVariable(value = "locationType", required = false) String locationType, @PathVariable(value = "excludeId", required = false) Long excludeId)
    {
        BaseLocation location = new BaseLocation();
        location.setLocationId(excludeId);
        if(locationType==null){
            location.setLocationType("05");
        }
        List<Ztree> ztrees = baseLocationService.selectLocationTreeExcludeChild(location);
        return ztrees;
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("base:location:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(BaseLocation location)
    {
        return toAjax(baseLocationService.changeStatus(location));
    }
    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("base:location:edit")
    @PostMapping("/changeAlarmStatus")
    @ResponseBody
    public AjaxResult changeAlarmStatus(BaseLocation location)
    {
        return toAjax(baseLocationService.changeAlarmStatus(location));
    }
}
